package cn.zebra.dev.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 未认证处理拦截器
 *
 * @author runnable@sina.cn
 */
public class UnauthorizedAccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        int status = HttpStatus.FORBIDDEN.value();
        response.setStatus(status);
        HashMap<String, Object> result = new HashMap<>(3);
        result.put("status", status);
        result.put("message", exception.getMessage());
        result.put("timestamp", System.currentTimeMillis());
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}
